<template>
  <div id="picture-manage-page">
    <!--    搜索-->
    <a-collapse v-model:activeKey="activeKeys" ghost>
      <a-collapse-panel key="1" header="筛选条件">
        <a-form layout="inline" class="search-form">
          <a-form-item label="关键词">
            <a-input
              v-model:value="params.searchText"
              @pressEnter="doSearch"
              placeholder="根据名称和简介查询"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="分类">
            <a-input
              v-model:value="params.category"
              @pressEnter="doSearch"
              placeholder="根据分类查询"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="标签">
            <a-input
              v-model:value="params.tags"
              @pressEnter="doSearch"
              placeholder="根据标签查询"
              allow-clear
            />
          </a-form-item>

          <a-form-item label="审核状态">
            <a-select
              v-model:value="params.reviewStatus"
              @change="doSearch"
              placeholder="根据审核状态查询"
              allow-clear
              style="width: 200px"
            >
              <a-select-option
                v-for="item in PIC_REVIEW_STATUS_OPTIONS"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item>
            <a-button type="primary" @click="doSearch">查询</a-button>
          </a-form-item>
        </a-form>
      </a-collapse-panel>

      <a-collapse-panel key="2" header="操作按钮">
        <div class="action-buttons">
          <a-space :size="16">
            <a-button type="primary" href="/picture/add">
              <template #icon><plus-outlined /></template>
              创建图片
            </a-button>

            <a-button type="dashed" href="/picture/upload-batch">
              <template #icon><upload-outlined /></template>
              批量上传图片
            </a-button>

            <a-button danger href="/picture/add/batch">
              <template #icon><import-outlined /></template>
              批量导入图片
            </a-button>
          </a-space>
        </div>
      </a-collapse-panel>
    </a-collapse>

    <!--    表格-->
    <a-table
      :columns="columns"
      :data-source="pictureList"
      :pagination="pagination"
      @change="doTableChange"
      :scroll="{ x: 1300 }"
      :rowKey="(record: API.Picture) => record?.id?.toString() || Math.random().toString()"
      :loading="loading"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'url'">
          <a-image
            :height="60"
            :width="60"
            :src="record.url"
            style="object-fit: cover"
            :preview="true"
          />
        </template>
        <template v-else-if="column.dataIndex === 'name'">
          <a-tooltip :title="record.name">
            <span>{{ record.name }}</span>
          </a-tooltip>
        </template>
        <template v-else-if="column.dataIndex === 'reviewStatus'">
          <a-tag
            :color="
              record.reviewStatus === 1
                ? 'success'
                : record.reviewStatus === 2
                  ? 'error'
                  : 'warning'
            "
          >
            {{
              record.reviewStatus === 1 ? '已通过' : record.reviewStatus === 2 ? '已拒绝' : '待审核'
            }}
          </a-tag>
        </template>
        <template v-else-if="column.dataIndex === 'pictureInfo'">
          <a-tooltip>
            <template #title>
              <a-descriptions :column="1" size="small">
                <a-descriptions-item label="格式">{{ record.picFormat }}</a-descriptions-item>
                <a-descriptions-item label="宽度">{{ record.picWidth }}</a-descriptions-item>
                <a-descriptions-item label="高度">{{ record.picHeight }}</a-descriptions-item>
                <a-descriptions-item label="宽高比">{{ record.picScale }}</a-descriptions-item>
                <a-descriptions-item label="大小">{{
                  formatSize(record.picSize)
                }}</a-descriptions-item>
              </a-descriptions>
            </template>
            <span>{{ record.picFormat }} | {{ record.picWidth }}x{{ record.picHeight }}</span>
          </a-tooltip>
        </template>
        <template v-else-if="column.dataIndex === 'reviewInfo'">
          <a-tooltip>
            <template #title>
              <a-descriptions :column="1" size="small">
                <a-descriptions-item label="审核人">{{ record.reviewerId }}</a-descriptions-item>
                <a-descriptions-item label="审核信息">{{
                  record.reviewMessage
                }}</a-descriptions-item>
                <a-descriptions-item label="审核时间">
                  {{ dayjs(record.reviewTime).format('YYYY-MM-DD HH:mm:ss') }}
                </a-descriptions-item>
              </a-descriptions>
            </template>
            <span>{{ record.reviewMessage || '无审核信息' }}</span>
          </a-tooltip>
        </template>
        <template v-else-if="column.dataIndex === 'tags'">
          <a-space wrap>
            <a-tag v-for="tag in JSON.parse(record.tags)" color="blue" :key="tag">{{ tag }}</a-tag>
          </a-space>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button
              v-if="record.reviewStatus === 0"
              type="primary"
              size="small"
              @click="reviewPicture(record.id, 1)"
            >
              <template #icon><check-outlined /></template>
              通过
            </a-button>
            <a-button
              v-if="record.reviewStatus === 0"
              danger
              size="small"
              @click="reviewPicture(record.id, 2)"
            >
              <template #icon><close-outlined /></template>
              拒绝
            </a-button>
            <a-button type="link" :href="`/picture/add?id=${record.id}`">
              <template #icon><edit-outlined /></template>
              编辑
            </a-button>
            <a-popconfirm
              title="确定要删除这张图片吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="doDeletePicture(record.id)"
            >
              <a-button danger size="small">
                <template #icon><delete-outlined /></template>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import dayjs from 'dayjs'
import {
  deletePictureUsingPost,
  listPictureByPageUsingGet,
  reviewPictureUsingPost,
} from '@/api/pictureController.ts'
import { formatSize } from '@/utils'
import { PIC_REVIEW_STATUS_OPTIONS } from '@/constants/picture.ts'
import { message } from 'ant-design-vue'
import {
  PlusOutlined,
  UploadOutlined,
  ImportOutlined,
  CheckOutlined,
  CloseOutlined,
  EditOutlined,
  DeleteOutlined,
} from '@ant-design/icons-vue'

const columns = [
  {
    title: '图片',
    dataIndex: 'url',
    fixed: 'left',
    width: 100,
  },
  {
    title: '名称',
    dataIndex: 'name',
    ellipsis: true,
    width: 120,
  },
  {
    title: '审核状态',
    dataIndex: 'reviewStatus',
    width: 100,
    responsive: ['md'],
  },
  {
    title: '类型',
    dataIndex: 'category',
    width: 100,
    responsive: ['lg'],
  },
  {
    title: '标签',
    dataIndex: 'tags',
    width: 150,
    responsive: ['lg'],
  },
  {
    title: '图片信息',
    dataIndex: 'pictureInfo',
    ellipsis: true,
    width: 200,
    responsive: ['xl'],
  },
  {
    title: '用户id',
    dataIndex: 'userId',
    width: 80,
    responsive: ['xl'],
  },
  {
    title: '修改时间',
    dataIndex: 'updateTime',
    width: 150,
    responsive: ['xl'],
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 150,
    responsive: ['xl'],
  },
  {
    title: '审核信息',
    dataIndex: 'reviewInfo',
    ellipsis: true,
    width: 200,
    responsive: ['xl'],
  },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
    width: 200,
  },
]

// 定义分页参数类型
interface TableParams {
  current: number
  pageSize: number
  sortField?: string
  sortOrder?: string
  searchText?: string
  category?: string
  tags?: string[]
  reviewStatus?: number
}

// 定义图片类型
interface Picture {
  id?: number
  url?: string
  name?: string
  category?: string
  tags?: string
  picFormat?: string
  picWidth?: number
  picHeight?: number
  picScale?: string
  picSize?: number
  userId?: number
  createTime?: string
  updateTime?: string
  reviewStatus?: number
  reviewerId?: number
  reviewMessage?: string
  reviewTime?: string
}

// 请求参数
const params = reactive<API.listPictureByPageUsingGETParams>({
  current: 1,
  pageSize: 10,
  sortField: 'update_time',
  sortOrder: 'descend',
})

// 折叠面板的激活状态
const activeKeys = ref<string[]>(['1'])

// 审核
const reviewPicture = async (id: number, status: number) => {
  console.log('审核')
  let reviewMessage
  if (status === 2) {
    reviewMessage = await prompt('请输入拒绝理由')
  }
  const res = await reviewPictureUsingPost({
    id: id,
    reviewStatus: status,
    reviewMessage: reviewMessage ?? '管理员通过审核',
  })
  if (res.data.code !== 0) {
    return
  }
  message.success('审核成功')
  await getPictureList()
}

// 获取数据
const pictureList = ref<API.Picture[]>([])
const total = ref<number>(0)
const loading = ref<boolean>(false)

const getPictureList = async () => {
  loading.value = true
  try {
    const res = await listPictureByPageUsingGet({ ...params })
    if (res.data.code !== 0 || !res.data.data) {
      pictureList.value = []
      total.value = 0
      return
    }
    pictureList.value = res.data.data.records || []
    total.value = res.data.data.total || 0
  } catch (error) {
    console.error('获取图片列表失败:', error)
    pictureList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 分页数据
const pagination = computed(() => {
  return {
    current: params.current,
    showQuickJumper: true,
    pageSize: params.pageSize,
    total: total.value,
    showSizeChanger: true,
    pageSizeOptions: ['5', '10', '20'],
    showTotal: (total: number) => `共 ${total} 条`,
  }
})

// 分页改变
const doTableChange = (page: { current: number; pageSize: number }) => {
  params.current = page.current
  params.pageSize = page.pageSize
  getPictureList()
}

// 查询
const doSearch = () => {
  params.current = 1
  getPictureList()
  console.log(params)
}

// 删除图片
const doDeletePicture = async (id: number) => {
  const res = await deletePictureUsingPost({ id })
  if (res.data.code !== 0) {
    return
  }
  await getPictureList()
}

// 页面渲染完成时，获取数据
onMounted(() => {
  getPictureList()
})
</script>

<style lang="scss" scoped>
#picture-manage-page {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;

  :deep(.ant-collapse) {
    background: transparent;
    border: none;

    .ant-collapse-item {
      background: #fff;
      border-radius: 8px;
      margin-bottom: 16px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

      .ant-collapse-header {
        font-size: 14px;
        color: #1f1f1f;
        padding: 12px 16px;
      }

      .ant-collapse-content {
        border-top: 1px solid #f0f0f0;
      }
    }
  }

  .search-form {
    padding: 16px;
    background: #fff;
    border-radius: 0 0 8px 8px;

    .ant-form-item {
      margin-bottom: 12px;

      .ant-form-item-label > label {
        font-size: 13px;
        color: #666;
      }

      .ant-input,
      .ant-select-selector {
        font-size: 13px;
      }
    }
  }

  .action-buttons {
    padding: 16px;
    background: #fff;
    border-radius: 0 0 8px 8px;

    .ant-btn {
      height: 32px;
      padding: 0 16px;
      font-size: 13px;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
      }
    }
  }

  .ant-table-wrapper {
    background: #fff;
    padding: 16px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

    .ant-table {
      font-size: 13px;

      .ant-table-thead > tr > th {
        background: #fafafa;
        font-weight: 500;
        font-size: 13px;
      }

      .ant-table-tbody > tr > td {
        padding: 8px;
      }

      .ant-image {
        height: 60px !important;
        width: 60px !important;
      }

      .ant-tag {
        margin: 2px;
        padding: 0 6px;
        font-size: 12px;
        line-height: 20px;
      }

      .ant-btn {
        font-size: 12px;
        padding: 0 8px;
        height: 24px;
        margin: 0 2px;
      }
    }
  }

  .ant-descriptions {
    font-size: 12px;

    .ant-descriptions-item-label {
      color: #666;
      font-weight: 500;
    }
  }

  .ant-pagination {
    margin-top: 16px;
    text-align: right;
    font-size: 12px;
  }
}

// 响应式优化
@media screen and (max-width: 768px) {
  #picture-manage-page {
    padding: 12px;

    .search-form,
    .action-buttons {
      padding: 12px;
    }

    .ant-table-wrapper {
      padding: 12px;
    }
  }
}
</style>
